<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="随访类型">
          <el-select v-model="listQuery.type" placeholder="请选择" clearable>
            <el-option label="健康随访" value="health"></el-option>
            <el-option label="疾病随访" value="disease"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="被随访人">
          <el-input v-model="listQuery.personName" placeholder="请输入被随访人姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="随访时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button type="primary" @click="handleCreate">新增随访记录</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column prop="id" label="ID" align="center" width="80"></el-table-column>
      <el-table-column prop="type" label="随访类型" align="center" width="120">
        <template slot-scope="{row}">
          <el-tag :type="row.type === 'health' ? 'success' : 'warning'">
            {{ row.type === 'health' ? '健康随访' : '疾病随访' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="personName" label="被随访人" align="center" width="120"></el-table-column>
      <el-table-column prop="policeOfficer" label="随访民辅警" align="center" width="120"></el-table-column>
      <el-table-column prop="followUpDate" label="随访时间" align="center" width="180">
        <template slot-scope="{row}">
          {{ row.followUpDate | parseTime('{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>
      <el-table-column prop="content" label="随访内容" align="center"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center" width="200"></el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogStatus === 'create' ? '新增随访记录' : '编辑随访记录'" :visible.sync="dialogVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-position="right" label-width="120px">
        <el-form-item label="随访类型" prop="type">
          <el-select v-model="temp.type" placeholder="请选择">
            <el-option label="健康随访" value="health"></el-option>
            <el-option label="疾病随访" value="disease"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="被随访人" prop="personName">
          <el-input v-model="temp.personName"></el-input>
        </el-form-item>
        <el-form-item label="随访民辅警" prop="policeOfficer">
          <el-input v-model="temp.policeOfficer"></el-input>
        </el-form-item>
        <el-form-item label="随访时间" prop="followUpDate">
          <el-date-picker
            v-model="temp.followUpDate"
            type="datetime"
            placeholder="请选择日期时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="随访内容" prop="content">
          <el-input type="textarea" v-model="temp.content" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="temp.remark" :rows="2"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import request from '@/utils/request'

export default {
  name: 'FollowUp',
  filters: {
    parseTime
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        pageSize: 10,
        type: undefined,
        personName: undefined,
        startDate: undefined,
        endDate: undefined
      },
      dateRange: [],
      dialogVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        type: '',
        personName: '',
        policeOfficer: '',
        followUpDate: '',
        content: '',
        remark: ''
      },
      rules: {
        type: [{ required: true, message: '请选择随访类型', trigger: 'change' }],
        personName: [{ required: true, message: '请输入被随访人姓名', trigger: 'blur' }],
        policeOfficer: [{ required: true, message: '请输入随访民辅警姓名', trigger: 'blur' }],
        followUpDate: [{ required: true, message: '请选择随访时间', trigger: 'change' }],
        content: [{ required: true, message: '请输入随访内容', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const { data } = await request({
          url: '/followUp/list',
          method: 'get',
          params: this.listQuery
        })
        this.list = data.records
        this.total = data.total
      } catch (error) {
        console.error('获取列表失败:', error)
      }
      this.listLoading = false
    },
    handleDateRangeChange(val) {
      if (val) {
        this.listQuery.startDate = val[0]
        this.listQuery.endDate = val[1]
      } else {
        this.listQuery.startDate = undefined
        this.listQuery.endDate = undefined
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        type: '',
        personName: '',
        policeOfficer: '',
        followUpDate: '',
        content: '',
        remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async createData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            await request({
              url: '/followUp/add',
              method: 'post',
              data: this.temp
            })
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '创建成功'
            })
            this.getList()
          } catch (error) {
            console.error('创建失败:', error)
          }
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            await request({
              url: '/followUp/update',
              method: 'put',
              data: this.temp
            })
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '更新成功'
            })
            this.getList()
          } catch (error) {
            console.error('更新失败:', error)
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await request({
            url: `/followUp/delete/${row.id}`,
            method: 'delete'
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        } catch (error) {
          console.error('删除失败:', error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
}
</style> 